<?php

namespace app\admin\controller\dahui;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 工资管理
 *
 * @icon fa fa-circle-o
 */
class Gongzi extends Backend
{

    /**
     * Gongzi模型对象
     * @var \app\admin\model\dahui\Gongzi
     */
    protected $model = null;

    protected $searchFields = 'id,idnumber,taobaoname,kehu.name,kehu.mobile,kehu.bankcardnumber';

    protected $noNeedRight = ['pldjzt0', 'pldjzt1', 'pldjzt2', 'audit', 'changetstatus4', 'gzls', 'addhis', 'editkehunote', 'changetstatus', 'changepaystatus', 'edit2', 'edit1', 'tbxx', 'dingdanuserinfo', 'adddduser'];

    protected $tuikuan = 0;
    protected $caozuo = 0;
    protected $audit = 0;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dahui\Gongzi;
        $this->view->assign("auditstatusList", $this->model->getAuditstatusList());
        $this->view->assign("paystatusList", $this->model->getPaystatusList());
        $this->view->assign("preprocessingList", $this->model->getPreprocessingList());
        $this->view->assign("refundornotList", $this->model->getRefundornotList());

        $this->assignconfig('audit', $this->auth->check('dahui/dingdan/audit'));
        $this->assignconfig('luru', $this->auth->check('dahui/dingdan/luru'));
        $this->assignconfig('caozuo', $this->auth->check('dahui/dingdan/caozuo'));
        $this->assignconfig('tuikuan', $this->auth->check('dahui/newtk/tuikuan'));

        $this->tuikuan = $this->auth->check('dahui/newtk/tuikuan');
        $this->caozuo = $this->auth->check('dahui/dingdan/caozuo');
        $this->audit = $this->auth->check('dahui/dingdan/audit');

        $dahui = $this->auth->check('dahui/dingdan/audit')
            && $this->auth->check('dahui/dingdan/luru') && $this->auth->check('dahui/dingdan/caozuo');
        $this->assignconfig('dahui', $dahui);
        $this->view->assign("dahui", $dahui);


        $Gongshi = new \app\admin\model\dahui\Gongshi;
        $companyList = collection($Gongshi->field('businesstype, name, minimumcardinality, proportion')->select())->toArray();
        $this->view->assign("companyList", $companyList);

        $minimumcardinality = 0;
        foreach ($companyList as $row) {
            $minimumcardinality = $row['minimumcardinality'];
            break;
        }
        $this->view->assign("minimumcardinality", $minimumcardinality);
        $this->assignconfig('minimumcardinality', $minimumcardinality);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['kehu'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->field("id,auditstatus,preprocessing,orderdate,opyear,taobaoname,ownedcompany,idnumber,payyear,agencyfees,sbbase,gjjbase,totalwages,r_wages")
                ->with(['kehu'])
                 ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            if ($limit == 0) {
                //导出
                foreach ($list as &$row) {
//                    $row['idnumber'] = $this->importstr($row['idnumber']);
                    $row['kehu']['bankcardnumber'] = $this->gshyhkh($row['kehu']['bankcardnumber']);
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function importstr($one) {

        return "' ".$one;
    }

    //格式化银行卡号
    function gshyhkh($str)
    {
        $bankcardnumber = preg_replace('/[\r\n]+/', '', $str);
        $bankcardnumber = str_replace(" ", "", $str);
//        if (strlen($bankcardnumber) > 10) {
//            $arr = str_split($bankcardnumber, 4);//4的意思就是bai每4个为一组
//            $bankcardnumber = implode(' ', $arr);
//        }
        $bankcardnumber = "' ".$bankcardnumber;
        return $bankcardnumber;
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['orderdate'] = date('Y-m-d H:i:s');

                    if (isset($params['preprocessing']) && $params['preprocessing'] == '是') {
                        //预处理

                    } else {
                        if (empty($params['payyear'])) {
                            $this->error(__('请输入代缴年月!'));
                        }
                        $total = $this->model
                            ->where('idnumber', $params['idnumber'])
                            ->where('payyear', $params['payyear'])
                            ->count();

                        if ($total > 0) {
                            $this->error(__('系统已存在同一客户工资代缴年月!'));
                        }
                    }

                    $params = $this->setquanxianlog($params);
                    $result = $this->model->allowField(true)->save($params);

                    if (isset($params['idnumber']) && strlen($params['idnumber']) > 10) {
                        $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $params['idnumber']]);
                        if ($kehu) {
                            $kehu->name = $params['name'];
                            $kehu->mobile = $params['mobile'];
                            $kehu->bankcardnumber = $params['bankcardnumber'];
                            $kehu->save();
                        } else {
                            $kehu = new \app\admin\model\dahui\Kehu;
                            $result2 = $kehu->allowField(true)->save($params);
                        }
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }

    /**
     * 编辑 订单管理
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $params = $this->setquanxianlog($params);
                    $result = $row->allowField(true)->save($params);

                    $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $row['idnumber']]);
                    if (!$kehu) {
                        $kehu = new \app\admin\model\dahui\Kehu;
                    } else if (isset($params['kehu.bankcardnumber'])) {
                        $kehu->bankcardnumber = $params['kehu.bankcardnumber'];
                        $kehu->save();
                    } else {
                        $result2 = $kehu->allowField(true)->save($params);
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $row['idnumber']]);
        if ($kehu) {
            $row['idnumber'] = $kehu->idnumber;
            $row['name'] = $kehu->name;
            $row['mobile'] = $kehu->mobile;
            $row['bankcardnumber'] = $kehu->bankcardnumber;
            $row['note'] = $kehu->note;
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 审核 订单管理
     */
    public function audit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    if (isset($params['preprocessing']) && $params['preprocessing'] == '是') {
                        $this->error(__('预处理的订单不能审核！'));
                    } else {
                        $params['preprocessing'] = '';
                    }

                    $params['auditstatus'] = '已审核';
                    $params = $this->setquanxianlog($params);
                    $result = $row->allowField(true)->save($params);

                    $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $params['idnumber']]);
                    if (!$kehu) {
                        $kehu = new \app\admin\model\dahui\Kehu;
                    }
                    $result2 = $kehu->allowField(true)->save($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $row['idnumber']]);
        if ($kehu) {
            $row['idnumber'] = $kehu->idnumber;
            $row['name'] = $kehu->name;
            $row['mobile'] = $kehu->mobile;
            $row['bankcardnumber'] = $kehu->bankcardnumber;
            $row['note'] = $kehu->note;
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 编辑 代缴明细
     */
    public function edit1($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->view->assign("refundornotList", $row->getRefundornotList());

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if (isset($params['kehu.mobile'])) {
                    $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $row->idnumber]);
                    $kehu->mobile = $params['kehu.mobile'];
                    $kehu->save();
                    $this->success('客户电话修改成功');
                } else if (isset($params['kehu.bankcardnumber'])) {
                    $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $row->idnumber]);
                    $kehu->bankcardnumber = $params['kehu.bankcardnumber'];
                    $kehu->save();
                    $this->success('客户银行卡修改成功');
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 编辑 代缴客户
     */
    public function edit2($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $msg = "代缴备注修改成功";
                if (isset($params['agencyfees'])) {
                    $row->agencyfees = $params['agencyfees'];
                    $msg = "付代理费修改成功";
                } else {
                    $row->paynote = $params['paynote'];
                }
                $row = $this->setquanxianlog2($row);
                $row->save();
                $this->success($msg);
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 编辑 退款客户
     */
    public function edit3($ids = null)
    {
        $row = \app\admin\model\dahui\Nianyue::get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->view->assign("refundornotList", $row->getRefundornotList());

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $row->refundornot = $params['refundornot'];
                $row->save();
                $this->success('退款状态修改成功');
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 代缴明细
     */
    public function index1()
    {
        if ($this->request->isAjax()) {
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);

            $idnumber = "";
            if (isset($filter['idnumber'])) {
                $idnumber = $filter['idnumber'];
            }

            if (empty($idnumber)) {
                return json(array("total" => 0, "rows" => array(), "idnumber" => $idnumber, "note" => ''));
            }

            $list = $this->model
                ->where('idnumber', $idnumber)
                ->where('auditstatus', '已审核')
                ->order('opyear desc')
                ->select();

            $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $idnumber])->toArray();

            $list = collection($list)->toArray();

            foreach ($list as &$row) {
                if ($limit == 0) {
                    //导出
//                    $row['idnumber'] = $this->importstr($row['idnumber']);
                    $row['kehu']['bankcardnumber'] = $this->gshyhkh($row['kehu']['bankcardnumber']);
                }

                $row['kehu'] = $kehu;
            }

            $result = array("total" => count($list), "rows" => $list, "idnumber" => $idnumber, "note" => $kehu['note']);

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 代缴客户
     */
    public function index2()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['kehu'])
                ->where($where)
                ->where('auditstatus', '已审核')
                ->where('refundornot', '')
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['kehu'])
                ->where($where)
                ->where('auditstatus', '已审核')
                ->where('refundornot', '')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            if ($limit == 0) {
                //导出
                foreach ($list as &$row) {
//                    $row['idnumber'] = $this->importstr($row['idnumber']);
                    $row['kehu']['bankcardnumber'] = $this->gshyhkh($row['kehu']['bankcardnumber']);
                }
            }
            $money = 0;
            foreach ($list as &$row) {
//              工资总额=实发工资+个税
//                应发工资=个税+实发工资
//工资总额 = 应发工资
                $y_wages = $row['y_wages'];
                if ($y_wages == 0) {
                    $y_wages = $row['totalwages'];
                }

                if ($row['r_wages'] == 0) {
                    $row['r_wages'] = $y_wages - $row['tax'];
                }

                $row['y_wages'] = $y_wages;
                $money += floatval($y_wages);
            }
            $result = array("total" => $total, "rows" => $list, "extend" => ['money' => sprintf("%.2f", $money)]);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 退款客户
     */
    public function index3()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['kehu'])
                ->where($where)
                ->where('refundornot', '<>', '')
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['kehu'])
                ->where($where)
                ->where('refundornot', '<>', '')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $money = 0;
            if ($limit == 0) {
                //导出
                foreach ($list as &$row) {
//                    $row['idnumber'] = $this->importstr($row['idnumber']);
                    $row['kehu']['bankcardnumber'] = $this->gshyhkh($row['kehu']['bankcardnumber']);

                }
            }
            foreach ($list as $row) {
                $money += floatval($row['totalwages']);
            }
            $result = array("total" => $total, "rows" => $list, "extend" => ['money' => sprintf("%.2f", $money)]);

            return json($result);
        }
        return $this->view->fetch();
    }

    //http://dahui.test/admin/dahui/gongzi/gzls?taobaoname=tb6687946_2011&idnumber=220105199108200020
    //显示此淘宝号，办理过的工资缴纳记录
    public function gzls()
    {
        $taobaoname = $this->request->request('taobaoname', '');
        $idnumber = $this->request->request('idnumber', '');
        if (!$taobaoname && !$idnumber) {
            $this->error('无效的的淘宝号或身份证号！');
        }

        if ($this->request->isAjax()) {
            if (!empty($taobaoname)) {
                $list = $this->model
                    ->with(['kehu'])
                    ->where('taobaoname', $taobaoname)
                    ->order('payyear', 'desc')
                    ->select();
            } else if (!empty($idnumber)) {
                $list = $this->model
                    ->with(['kehu'])
                    ->where('gongzi.idnumber', $idnumber)
                    ->order('payyear', 'desc')
                    ->select();
            }

            $total = count($list);

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        } else {
            //这一招怪异么？
            $this->assignconfig('taobaoname', $taobaoname);
            $this->assignconfig('idnumber', $idnumber);
        }

        return $this->view->fetch();
    }

    //加入工资缴纳记录
    public function addhis($ids)
    {
        $this->relationSearch = true;
        if ($this->request->isPost()) {
            $gz = $this->model
                ->with(['kehu'])
                ->where('gongzi.id', $ids)
                ->find();

            if ($gz) {
                $this->success('success', null, $gz);
            }
        }
        $this->error(__('没有选中工资缴纳记录'));
    }

    public function tbxx($taobaoname) {
        $data = [
            'idnumber'   => '',
            'kehuname'   => '',
            'kehumobile' => '',
            'bankcardnumber' => '',
            'sbbase' => 0,
            'gjjbase' => 0,
            'taobaoname'   => '',
            'totalwages'   => 0,
            'isgz'   => 0,

        ];
        $dingdan = \app\admin\model\dahui\Dingdan::where('taobaoname', $taobaoname)
            ->where('businesstype', '社保')
            ->order('id', 'DESC')
            ->find();

        if ($dingdan) {
            $kehu = \app\admin\model\dahui\Kehu::where('idnumber', $dingdan->idnumber)->find();
            if ($kehu) {
                $data['kehuname'] = trim($kehu['name']);
                $data['kehumobile'] = trim($kehu['mobile']);
                $data['bankcardnumber'] = $kehu['bankcardnumber'];
            }
            $data['idnumber'] = $dingdan['idnumber'];
            $data['taobaoname'] = $dingdan['taobaoname'];
            $data['sbbase'] = $dingdan['paymentbase'];
            $data['ownedcompany'] = $dingdan['payingcompany'];
        }

        $dingdan2 = \app\admin\model\dahui\Dingdan::where('taobaoname', $taobaoname)
            ->where('businesstype', '公积金')
            ->order('id', 'DESC')
            ->find();
        if ($dingdan2) {
            $data['gjjbase'] = $dingdan2['paymentbase'];
        }

        $gz = $this->model
            ->where('taobaoname', $taobaoname)
            ->order('id', 'DESC')
            ->find();

        //淘宝账号，所属公司、姓名、身份证号、客户电话、社保基数、公积金基数，个税
        if ($gz) {
            $data['isgz'] = 1;
        }

        $this->success('success', null, $data);
    }

    //http://dahui.test/admin/dahui/gongzi/gzls?taobaoname=tb6687946_2011
    //显示此淘宝号，办理过的个人订单信息
    public function dingdanuserinfo($taobaoname)
    {
        if (!$taobaoname) {
            $this->error('无效的的淘宝号');
        }

        if ($this->request->isAjax()) {
            $list = \app\admin\model\dahui\Dingdanuser::where('taobaoname', $taobaoname)->select();
            $total = count($list);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        } else {
            $list0 = \app\admin\model\dahui\Dingdan::where('taobaoname', $taobaoname)
                ->field('idnumber')
                ->group("idnumber")
                ->select();
            foreach ($list0 as $row0) {
                $dingdanuser = \app\admin\model\dahui\Dingdanuser::where('idnumber', $row0['idnumber'])->find();
                if (!$dingdanuser) {
                    $dingdanuser = new \app\admin\model\dahui\Dingdanuser();
                }

                $dingdanuser->taobaoname = $taobaoname;
                $dingdanuser->idnumber = $row0['idnumber'];

                $kehu = \app\admin\model\dahui\Kehu::where('idnumber', $row0['idnumber'])->find();
                if ($kehu) {
                    $dingdanuser->name = trim($kehu['name']);
                    $dingdanuser->mobile = trim($kehu['mobile']);
                    $dingdanuser->bankcardnumber = $kehu['bankcardnumber'];
                }

                $sb = \app\admin\model\dahui\Dingdan::where('idnumber', $row0['idnumber'])
                    ->where('businesstype', '社保')
                    ->order('id', 'DESC')
                    ->limit(1)
                    ->find();
                //社保必需有
                if ($sb) {
                    $dingdanuser->sbbase = $sb['paymentbase'];
                    $dingdanuser->payingcompany = $sb['payingcompany'];
                }

                $gjj = \app\admin\model\dahui\Dingdan::where('idnumber', $row0['idnumber'])
                    ->where('businesstype', '公积金')
                    ->order('id', 'DESC')
                    ->limit(1)
                    ->find();

                if ($gjj) {
                    $dingdanuser->gjjbase = $gjj['paymentbase'];
                }

                $gs = \app\admin\model\dahui\Dingdan::where('idnumber', $row0['idnumber'])
                    ->where('businesstype', '个税')
                    ->order('id', 'DESC')
                    ->limit(1)
                    ->find();

                if ($gs) {
                    $dingdanuser->tax = $gs['paymentamount'];
                }

                //上次工资缴纳
                $gz = $this->model
                    ->where('idnumber', $row0['idnumber'])
                    ->order('payyear', 'desc')
                    ->limit(1)
                    ->find();

                if ($gz) {
                    $dingdanuser->opyear = $gz['opyear'];
                    $dingdanuser->payyear = $gz['payyear'];
                    $dingdanuser->agencyfees = $gz['agencyfees'];
                    $r_wages = $gz['r_wages'];
                    if ($r_wages == 0) {
                        $r_wages = $gz['totalwages'] -  $gz['tax'];
                    }
                    $dingdanuser->totalwages = $r_wages;// 实发工资
                }

                $dingdanuser->save();
            }

            $this->assignconfig('taobaoname', $taobaoname);
        }

        return $this->view->fetch();
    }

    public function adddduser($ids)
    {
        if ($this->request->isPost()) {
            $dd = \app\admin\model\dahui\Dingdanuser::get($ids);
            if ($dd) {
                $this->success('success', null, $dd);
            }
        }
        $this->error(__('没有选中记录'));
    }


    /**
     * 编辑 客户备注
     */
    public function editkehunote()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $idnumber = $params['idnumber'];
                $kehu = \app\admin\model\dahui\Kehu::get(['idnumber' => $idnumber]);
                $kehu->note = $params['note'];
                $kehu->save();
                $this->success('客户备注修改成功');
            }
            $this->error(__('Parameter %s can not be empty', ''));
        } else {
            $idnumber = $this->request->request('idnumber');
            $kehu = \app\admin\model\dahui\Kehu::where('idnumber', $idnumber)
                ->field('note')
                ->find();
            $row = [];
            $row['note'] = $kehu['note'];
            $row['idnumber'] = $idnumber;
            $this->view->assign("row", $row);
        }

        return $this->view->fetch();
    }

    /**
     * 是否退款 状态
     */
    //http://dahui.test/admin/dahui/gongzi/changetstatus
    public function changetstatus($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->tuikuan) {
            if ($row->refundornot == '') {
                $row->refundornot = '待退款';
            } else if ($row->refundornot == '待退款') {
                $row->refundornot = '已退款';
            } else if ($row->refundornot == '已退款') {
                $row->refundornot = '需退款';
            } else if ($row->refundornot == '需退款') {
                $row->refundornot = '';
            }
        } else if ($this->caozuo) {
            if ($row->refundornot == '') {
                $row->refundornot = '需退款';
            } else if ($row->refundornot == '需退款') {
                $row->refundornot = '';
            }
        } else if ($this->audit) {
            if ($row->refundornot == '') {
                $row->refundornot = '待退款';
            } else if ($row->refundornot == '待退款') {
                $row->refundornot = '需退款';
            } else if ($row->refundornot == '需退款') {
                $row->refundornot = '';
            }
        }

        $row->save();
        $this->success("退款状态修改成功", null, ['refundornot' => $row->refundornot]);
    }

    //退款员
    //从待退款状态 点击后 变更为 已退款（另外有时候误操作情况下 他可以把已退款变更为  --状态 让其他角色重新操作）
    public function changetstatus4($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row->refundornot == '待退款') {
            $row->refundornot = '已退款';
        } else if ($row->refundornot == '已退款') {
            $row->refundornot = '';
        } else if ($row->refundornot == '') {
            $row->refundornot = '已退款';
        }
//        $row = $this->setquanxianlog2($row);

        $row->save();
        $this->success("退款状态修改成功", null, ['refundornot' => $row->refundornot]);

    }

    /**
     * 代缴状态++
     */
    //http://dahui.test/admin/dahui/gongzi/changepaystatus
    public function changepaystatus($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row->paystatus == '未办理') {

            $row->paystatus = '办理失败';
        } else if ($row->paystatus == '已办理') {
            $row->paystatus = '未办理';
        } else if ($row->paystatus == '办理失败') {
            $row->paystatus = '已办理';

        }

        $row->save();
        $this->success("代缴状态修改成功", null, ['paystatus' => $row->paystatus]);
    }

    //设置权限记录
    function setquanxianlog($params)
    {
        if (!$params) {
            return $params;
        }
        $audit = $this->auth->check('dahui/dingdan/audit');
        $luru = $this->auth->check('dahui/dingdan/luru');
        $caozuo = $this->auth->check('dahui/dingdan/caozuo');
        $admin = $audit;

        if ($audit) {
            //审核员和管理员
            $params['auditman'] = $this->auth->nickname;
        } else if ($luru) {
            $params['luruman'] = $this->auth->nickname;
        } else if ($caozuo) {
            $params['opman'] = $this->auth->nickname;
        }

        return $params;
    }

    function setquanxianlog2($row)
    {
        if (!$row) {
            return $row;
        }
        $audit = $this->auth->check('dahui/dingdan/audit');
        $luru = $this->auth->check('dahui/dingdan/luru');
        $caozuo = $this->auth->check('dahui/dingdan/caozuo');
        $admin = $audit;

        if ($audit) {
            //审核员和管理员
            $row->auditman = $this->auth->nickname;
        } else if ($luru) {
            $row->luruman = $this->auth->nickname;
        } else if ($caozuo) {
            $row->opman= $this->auth->nickname;
        }

        return $row;
    }

    /**
     * 批量代缴状态
     */
    public function pldjzt0($ids = null)
    {
        $list = $this->model
            ->where('id', 'in', $ids)
            ->select();

        foreach ($list as $row) {
            $row->paystatus = '已办理';
            $row->save();

        }
        $this->success();
    }

    public function pldjzt1($ids = null)
    {
        $list = $this->model
            ->where('id', 'in', $ids)
            ->select();

        foreach ($list as $row) {
            $row->paystatus = '未办理';
            $row->save();

        }
        $this->success();
    }

    public function pldjzt2($ids = null)
    {
        $list = $this->model
            ->where('id', 'in', $ids)
            ->select();

        foreach ($list as $row) {
            $row->paystatus = '办理失败';
            $row->save();

        }
        $this->success();
    }



}
